use std::mem::MaybeUninit;

use actix_web::{dev::ServerHandle, App, HttpServer};

use crate::{cfg::WEB_SERVE_ADDR, error::AppErr};


mod api;

mod req;
mod res;
mod session;

static mut SERVER: MaybeUninit<ServerHandle> = MaybeUninit::uninit();

pub async fn stop() {
    let handle = unsafe {
        SERVER.assume_init_ref()
    };
    handle.stop(true).await;
}

pub async fn init() -> Result<(), AppErr> {

    session::init();

    let app = || {
        App::new()
            .configure(api::register)
    };

    let serve = HttpServer::new(app)
        .bind(WEB_SERVE_ADDR)?
        .run();

    unsafe { SERVER.write(serve.handle()); }

    serve.await?;

    Ok(())
}
